//
//  HasInstalledPowerTableViewCell.m
//  GetPowerDBO
//
//  Created by 周博 on 2017/7/13.
//  Copyright © 2017年 BogoZhou. All rights reserved.
//

#import "HasInstalledPowerTableViewCell.h"
#import "UIImage+GIF.h"
#import "BorderHelper.h"
#import "GetQRCodeViewController.h"

@interface HasInstalledPowerTableViewCell ()
{
    
}
@property (nonatomic,strong) MBProgressHUD *hub;

@end

@implementation HasInstalledPowerTableViewCell

- (void)awakeFromNib {
    [super awakeFromNib];
    // Initialization code
    UITapGestureRecognizer *tapRecognizerTel=[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(callFun)];
    
    _labelMerTel.userInteractionEnabled=YES;
    [_labelMerTel addGestureRecognizer:tapRecognizerTel];
    
    UITapGestureRecognizer *tapRecognizerAddress=[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(addresslFun)];
    
    _labelAddress.userInteractionEnabled=YES;
    [_labelAddress addGestureRecognizer:tapRecognizerAddress];
    
    [self setButtonUI];
}

- (void)showDataWithModel:(HasInstalledModel *)model{
    model.shop = [[ShopModel alloc] init];
    [model.shop setValuesForKeysWithDictionary:model.store_info];
    
    _myModel = model;
    
    [_imageViewDianliangGreen removeFromSuperview];
    _imageViewDianliangGreen = nil;
    _imageViewDianliangGreen = [[UIImageView alloc] init];
    _imageViewDianliangGreen.backgroundColor = kGreenColor;
    [self addSubview:_imageViewDianliangGreen];
    
    //店名
    _labelShopName.text = model.shop.name;
    
    //老板
    _labelMerName.text = model.shop.contact;
    
    //老板联系方式
    _labelMerTel.text = model.shop.tel;
    
    //电量
    _labelPower.text = [NSString stringWithFormat:@"%ld%%",model.dump_energy.integerValue];
    if (model.dump_energy.integerValue == 100) {
        _imageViewDianliang.image = [UIImage imageNamed:@"lvdianliang"];
        _imageViewDianliangGreen.hidden = YES;
        _imageViewDianliangGreen.frame = CGRectMake(55.5, 109.5, 9, 14);

    }else{
        double bili = model.dump_energy.doubleValue/100;
        _imageViewDianliang.image = [UIImage imageNamed:@"dianliang"];
        _imageViewDianliangGreen.hidden = NO;
        _imageViewDianliangGreen.frame = CGRectMake(55.5, 123.5 -(14 * bili) , 9, 14 * bili);
    }
    
    
    
    //充电宝编号
    _labelNum.text = model.alias;
    
    //固件版本号
    _labelVerson.text = [BGFunctionHelper isNULLOfString:model.firmware_version] ? @"" : model.firmware_version;
    
    //在线天数
    _labelDays.text = model.total_online_count;
    
    //充电次数
    _labelTimes.text = model.total_charging_count;
    
    //位置
    _labelAddress.text = [NSString stringWithFormat:@"%@%@",model.shop.area_name,model.shop.specific_address];
    
    NSString *dateString;
    
    //时间
    if (model.on_line.integerValue == 0) {//不在线
        
        if ([BGFunctionHelper isNULLOfString:model.offline_time]) {
            dateString = @"该设备还未被使用";
        }else{
            dateString = model.offline_time;
        }
        _labelDate.text = dateString;
        
        _imageViewDate.image = [UIImage imageNamed:@"xiaxianshijian"];
        _imageViewLeftType.image = [UIImage imageNamed:@"28_WiFi02"];
//        _labelDate.text = model.offline_time;
        _buttonCheck.hidden = NO;
    }else{
        
        if ([BGFunctionHelper isNULLOfString:model.online_time]) {
            dateString = @"该设备还未被使用";
        }else{
            dateString = model.online_time;
        }
        _labelDate.text = dateString;
        
        _imageViewDate.image = [UIImage imageNamed:@"shangxianshijian"];
        _imageViewLeftType.image = [UIImage imageNamed:@"28_WiFi"];
        _labelDate.text = model.online_time;
        _buttonCheck.hidden = YES;
    }
    
    //右侧灯状态
    if (model.green_light_status.integerValue == 0) {//已关闭
        _imageViewRightType.image = [UIImage imageNamed:@"guanbi"];
    }else if (model.green_light_status.integerValue == 1){//闪烁
        NSString *path = [[NSBundle mainBundle] pathForResource:@"shanshuo" ofType:@"gif"];
        NSData *data = [NSData dataWithContentsOfFile:path];
        UIImage *image = [UIImage sd_animatedGIFWithData:data];
        _imageViewRightType.image = image;
    }else{//常亮
        _imageViewRightType.image = [UIImage imageNamed:@"changliang"];
    }
    
    if (model.on_line.integerValue == 0) {//离线，显示离线原因
        _labelReasonLeft.hidden = NO;
        _labelReason.hidden = NO;
        _labelReason.textAlignment = NSTextAlignmentLeft;
        
        _labelReason.backgroundColor = kWhiteColor;
        _labelReason.textColor = kDateGrayColor;
        
//        _labelReason.text = [NSString stringWithFormat:@"电量：%ld%%",model.dump_energy.integerValue];
        
        if (model.offline_message_status.integerValue == 0) {//未联网或未开机
            _labelReason.text = @"未联网或未开机";
        }else{
            if (model.dump_energy.integerValue < 10) {
                _labelReason.text = @"低电量自动关机";
            }else{
                _labelReason.text = @"充电宝已关机";
            }
        }
    }else{
        _labelReasonLeft.hidden = YES;
//        [_labelReason removeFromSuperview];
//        [self updateFocusIfNeeded];
        _labelReason.hidden = YES;
    }
    
    //涨粉数
    _labelZhangF.text = [NSString stringWithFormat:@"%ld (今日)",model.sub_count.integerValue];
}

- (IBAction)getQRCodeButtonClick:(UIButton *)sender {
    NSString *wifiCode = @"https://www.wacdd.com/rd/device/";
    NSString *mimaCode = @"https://www.wacdd.com/rd/device_pwd/";
    NSString *resaultCode;
    
    if (_myModel.device_type.integerValue == 1) {
        resaultCode = [NSString stringWithFormat:@"%@%@",wifiCode,_myModel.alias];
    }else{
        resaultCode = [NSString stringWithFormat:@"%@%@",mimaCode,_myModel.alias];
    }
    
    UIStoryboard *storyboard = kMainStroyboard;
    GetQRCodeViewController *qrCodeVC = [storyboard instantiateViewControllerWithIdentifier:@"GetQRCodeViewController"];
    _myModel.shop = [[ShopModel alloc] init];
    [_myModel.shop setValuesForKeysWithDictionary:_myModel.store_info];
    qrCodeVC.model = _myModel.shop;
    qrCodeVC.alias = _myModel.alias;
    qrCodeVC.resaultCode = resaultCode;
    qrCodeVC.modalPresentationStyle = UIModalPresentationOverFullScreen;
    [[self viewController] presentViewController:qrCodeVC animated:YES completion:nil];
}



- (UIViewController *)viewController {
    UIResponder *next = self.nextResponder;
    do {
        //判断响应者是否为视图控制器
        if ([next isKindOfClass:[UIViewController class]]) {
            return (UIViewController *)next;
        }
        next = next.nextResponder;
    } while (next != nil);
    
    return nil;
}

- (void)callFun{
    
    NSMutableString *str=[[NSMutableString alloc] initWithFormat:@"tel:%@",_labelMerTel.text];
    UIWebView *callWebview = [[UIWebView alloc] init];
    [callWebview loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:str]]];
    [[self viewController].view addSubview:callWebview];
}

- (void)addresslFun{
    [self alertVCByTitle:_labelAddress.text];
}

- (void)setButtonUI{
//    _buttonCheck
    [BorderHelper setBorderWithColor:kGreenColor button:_buttonCheck];
}

//检查在线
- (IBAction)checkOnlineButtonClick:(UIButton *)sender {
//    kAlert(@"检查在线");
    [self checkFunc];
}


- (void)checkFunc{
    [self.hub hideAnimated:YES];
    
    self.hub = [MBProgressHUD showHUDAddedTo:[self viewController].view animated:YES];
    
    // Set the label text.
    self.hub.label.text = NSLocalizedString(@"正在检测...", @"HUD loading title");
//    NSLog(@"%@",_labelNum.text);
    [[AFClient shareInstance] checkTypeGetPowerByEid:kUserId alias:_labelNum.text progressBlock:nil success:^(id responseBody) {
        [self.hub hideAnimated:YES];
        if ([responseBody[@"code"] integerValue] == 200) {
            NSString *messageId = responseBody[@"data"];
            
            __block HasInstalledPowerTableViewCell*weakSelf = self;
            dispatch_time_t delayTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0/*延迟执行时间*/ * NSEC_PER_SEC));
            
            dispatch_after(delayTime, dispatch_get_main_queue(), ^{
                [weakSelf checkLinkByMessageId:messageId];
            });
            
        }else{
            [self alertVCByTitle:responseBody[@"message"]];
        }
    } failure:^(NSError *error) {
        [self.hub hideAnimated:YES];
    }];
}

//检查链路
- (void)checkLinkByMessageId:(NSString *)messageId{
    [self.hub hideAnimated:YES];
    
    self.hub = [MBProgressHUD showHUDAddedTo:[self viewController].view animated:YES];
    
    // Set the label text.
    self.hub.label.text = NSLocalizedString(@"请稍后...", @"HUD loading title");
    [[AFClient shareInstance] checkPostToPowerByMessage_id:messageId progressBlock:nil success:^(id responseBody) {
        [self.hub hideAnimated:YES];
        if ([responseBody[@"code"] integerValue] == 200) {
            [self alertVCByTitle:@"该充电宝当前实时在线"];
        }else{
            [self alertVCByTitle:responseBody[@"message"]];
        }
    } failure:^(NSError *error) {
        [self.hub hideAnimated:YES];
    }];
}

- (void)alertVCByTitle:(NSString *)title{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:title preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
    }];
    
    [alert addAction:action];
    [[self viewController] presentViewController:alert animated:YES completion:nil];
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}

@end
